#include "MemoryFileFormat.h"

/**
 *
 **/
MemoryFileFormat::MemoryFileFormat(PFSInfo info) : AbstractFileFormat(info) {
	//Filesystem::debug("MemoryFileFormat("+info->path+")");
    if(info->rwMode == true || info->writeMode == true) {
		PMemoryFile data = info->filesystem->getMemoryFile(info->path, info->isCache);
        if(data == NULL) {
			//Filesystem::debug("MemoryFileFormat( new )");
            info->filesystem->addMemoryFile(info);
        }
    }
}

/**
 *
 **/
MemoryFileFormat::~MemoryFileFormat() {
	//Filesystem::debug("~MemoryFileFormat()");
}

/**
 *
 **/
int MemoryFileFormat::close(PFSInfo info) {
	//Filesystem::debug("MemoryFileformat::close("+info->path+")");
	PMemoryFile data = info->filesystem->getMemoryFile(info->path, info->isCache);
    if(data != NULL) {
        data->read = false;
        data->write = false;
    }
    return 0;
}

/**
 *
 **/
int MemoryFileFormat::read(PFSInfo info) {
	//Filesystem::debug("MemoryFileformat::read("+info->path+")");
	PMemoryFile data = info->filesystem->getMemoryFile(info->path, info->isCache);

    if( data != NULL) {
        data->read = true;
        if (info->offset < data->size) {
            if ( (info->offset + info->size) > data->size) {
                info->size = data->size - info->offset;
            }
            memcpy(info->readBuffer, (char*)data->fileContent + info->offset, info->size);
        }
        else info->size = 0;
    }
    return info->size;
}

/**
 *
 **/
int MemoryFileFormat::write(PFSInfo info) {
	//Filesystem::debug("MemoryFileformat::write("+info->path+")");
	PMemoryFile data = info->filesystem->getMemoryFile(info->path, info->isCache);

    if( data == NULL ) {
        info->filesystem->addMemoryFile(info);
		data = info->filesystem->getMemoryFile(info->path, info->isCache);
    }
	if(data != NULL)
	{
		data->write = true;
		if( (info->offset+info->size) > data->size)
		{
			if((data->fileContent = realloc(data->fileContent, info->offset + info->size)) == NULL)
			{
				free(data->fileContent);
				return -ENOMEM;
			}
			data->memSize = info->offset+info->size;
		}

		memcpy((char*)data->fileContent + info->offset, (char*)info->writeBuffer, info->size);

		if( (info->offset+info->size) > data->size) {
			data->size = info->offset+info->size;
		}

	}
    return info->size;
}
